/*页面初始化函数*/
function init() {
    let layer = layui.layer, form = layui.form;

    let token = localStorage.getItem("token");

    if (token === null) {
        layer.msg("未登录，请登录", {icon: 5}, function () {
            window.location.href = "/login.html";
        })
        return false;
    }
    // let init_load_index = layer.load(1, {shade: [0.8, "#cccccc"]});//打开加载层
    $.get("/user/myInfo", {"token": token}, function (result) {
        if (result.code === 200) {
            /*检查角色*/
            if (!checkRole(result.data.roleName))
                return false;
            // 点击首页
            $("#index_btn").click();
            $("input[name='phone']").val(result.data.phone);
            $("input[name='username']").val(result.data.username);
            $("input[name='role_name']").val(result.data.roleName);
            $("input[name='address']").val(result.data.address);
            check_sex(result.data.sex);
            $("input[name='email']").val(result.data.email);
            $("input[name='head_portrait_url']").val(result.data.headPortraitUrl);
            $("input[name='blog_number']").val(result.data.blogNumber);
            $("input[name='comment_number']").val(result.data.commentNumber);
            check_username_head_portrait(result.data.username, result.data.headPortraitUrl);
        } else if (result.code === 401) {
            localStorage.removeItem("token");
            sessionStorage.clear();
            layer.alert(result.msg, {icon: 5}, function (index) {
                window.location.href = "/login.html";
                layer.close(index);
            })
        } else
            layer.msg(result.msg, {icon: 5});

        //layer.close(init_load_index);//关闭加载层
        layer.closeAll("loading");//关闭加载层
    })
}

/*选择性别的函数*/
function check_sex(sex) {
    $("input[name='sex']").prop("checked", false);
    $("input[name='sex'][value='" + sex + "']").prop("checked", true);
    layui.form.render("radio");//刷新单选框
}

/*检查头像和用户名的函数*/
function check_username_head_portrait(username, headPortraitUrl) {
    let $username = $("#span_username");
    if ($username.html() !== username) {
        $username.html(username);
    }
    let $url = $("#img_head_portrait_url");
    if ($url.attr("src") !== headPortraitUrl) {
        $url.attr("src", headPortraitUrl);
    }
}

layui.use(['form', 'layer'], function () {
    let layer = layui.layer,
        form = layui.form,
        $ = layui.$;

    // 1.查看按钮
    $("#user_info_btn").click(function () {
        $("#submitBtnDiv").prop("hidden", true);
        $("input[name='phone']").prop("disabled", true);
        $("input[name='username']").prop("disabled", true);
        $("input[name='role_name']").prop("disabled", true);
        $("input[name='address']").prop("disabled", true);
        $("input[name='sex']").prop("disabled", true);
        $("input[name='email']").prop("disabled", true);
        $("input[name='head_portrait_url']").prop("disabled", true);
        $("input[name='blog_number']").prop("disabled", true);
        $("input[name='comment_number']").prop("disabled", true);

        // 打开layer
        layer.open({
            type: 1,
            title: '个人信息',
            content: $("#userInfoLayer"),
            closeBtn: 2,
            area: ["300px", "400px"],
            anim: 3,
            end: function () {
                $("#userInfoLayer").css("display", "none");
            }
        })
    })
    // 2.修改按钮
    $("#userInfoEditBtn").click(function () {
        $("#submitBtnDiv").prop("hidden", false);
        $("input[name='phone']").prop("disabled", true);
        let $username = $("input[name='username']").prop("disabled", false);
        $("input[name='role_name']").prop("disabled", true);
        let $address = $("input[name='address']").prop("disabled", false);
        $("input[name='sex']").prop("disabled", false);
        $("input[name='email']").prop("disabled", true);
        let $head_portrait_url = $("input[name='head_portrait_url']").prop("disabled", false);
        $("input[name='blog_number']").prop("disabled", true);
        $("input[name='comment_number']").prop("disabled", true);

        let username = $username.val();
        let address = $address.val();
        let sex = $("input[name='sex']:checked").val();
        let head_portrait_url = $head_portrait_url.val();

        let edit_layer_index = layer.open({
            type: 1,
            title: '个人信息',
            content: $("#userInfoLayer"),
            closeBtn: 2,
            area: ["300px", "400px"],
            anim: 3,
            cancel: function (index, layero) {
                // 值复原
                $username.val(username);
                $address.val(address);
                check_sex(sex);
                $head_portrait_url.val(head_portrait_url);
                layer.close(index);
            },
            end: function () {
                $("#userInfoLayer").css("display", "none");
            }
        })
        // 2.1 更新按钮
        form.on('submit(formSubmit)', function (data) {
            //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
            //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
            //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            let update_load_index = layer.load(1);
            $.ajax({
                url: "/user/myInfo",
                method: "put",
                dataType: "json",
                data: {
                    "token": localStorage.getItem("token"),
                    "username": $.trim(data.field.username),
                    "head_portrait_url": $.trim(data.field.head_portrait_url),
                    "address": $.trim(data.field.address),
                    "sex": $.trim(data.field.sex),
                },
                success: function (result) {
                    if (result.code === 200) {
                        layer.close(edit_layer_index);
                        sessionStorage.clear();//清空用户名和头像信息
                        // 刷新头像和用户名
                        check_username_head_portrait(data.field.username, data.field.head_portrait_url);
                    } else
                        layer.msg(result.msg, {icon: 5});
                    layer.close(update_load_index);
                }
            })
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
        // 2.2 取消按钮
        $("#cancelBtn").click(function () {
            layer.close(edit_layer_index);
            // 值复原
            $username.val(username);
            $address.val(address);
            check_sex(sex);
            $head_portrait_url.val(head_portrait_url);
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        })
    })

    // 3.退出按钮
    $("#logout_btn").click(function () {
        localStorage.removeItem("token");
        sessionStorage.clear();
        window.location.href = "/blog/index.html";
    })
    // 开始初始化
    init();
})

/*检查角色的函数*/
function checkRole(role_name) {
    let layer = layui.layer;
    if (role_name !== "root") {
        if (role_name !== "publisher") {
            layer.alert("权限不足", function (index) {
                layer.close(index);
                window.location.href = "/index.html";
            })
            return false;
        } else {
            //暂时不对publisher角色作限制
        }
    }
    $("#ul_left").prop("hidden", false);
    return true;
}